const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, data } = event
  
  console.log('业务管理云函数调用:', { action, openid: wxContext.OPENID })
  
  try {
    switch (action) {
      // 订单管理
      case 'createOrder':
        return await createOrder(wxContext, data)
      case 'getOrders':
        return await getOrders(wxContext, data)
      case 'getUserOrders':
        return await getUserOrders(wxContext, data)
      case 'updateOrderStatus':
        return await updateOrderStatus(wxContext, data)
      case 'getOrderDetail':
        return await getOrderDetail(wxContext, data)
      case 'getOrderHistory':
        return await getOrderHistory(wxContext, data)
      
      // 项目管理
      case 'createProject':
        return await createProject(wxContext, data)
      case 'getProjects':
        return await getProjects(wxContext, data)
      case 'updateProject':
        return await updateProject(wxContext, data)
      case 'getProjectDetail':
        return await getProjectDetail(wxContext, data)
      
      // 服务管理
      case 'getServices':
        return await getServices()
      case 'bookService':
        return await bookService(wxContext, data)
      
      // 统计数据
      case 'getStats':
        return await getStats(wxContext)

      // 批量创建服务项目
      case 'batchCreateServices':
        return await batchCreateServices(wxContext, data)

      // 修复订单serviceId关联
      case 'fixOrderServiceId':
        return await fixOrderServiceId(wxContext, data)

      // 提交客服留言
      case 'submitMessage':
        return await submitMessage(wxContext, data)

      // 记录客服咨询
      case 'logCustomerService':
        return await logCustomerService(wxContext, data)

      // 取消订单
      case 'cancelOrder':
        return await cancelOrder(wxContext, data)

      // 申请取消订单
      case 'requestCancelOrder':
        return await requestCancelOrder(wxContext, data)

      // 处理取消申请
      case 'processCancelRequest':
        return await processCancelRequest(wxContext, data)

      // 管理员功能
      case 'getAdminOrders':
        return await getAdminOrders(wxContext, data)
      
      case 'getAdminStats':
        return await getAdminStats(wxContext, data)
      
      case 'assignTeam':
        return await assignTeam(wxContext, data)

      // 团队订单管理
      case 'getTeamOrders':
        return await getTeamOrders(wxContext, data)
      
      case 'acceptTeamOrder':
        return await acceptTeamOrder(wxContext, data)
      
      case 'updateOrderProgress':
        return await updateOrderProgress(wxContext, data)

      // 通知管理
      case 'sendNotification':
        return await sendNotification(wxContext, data)

      // 数据导出
      case 'exportOrderData':
        return await exportOrderData(wxContext, data)

      default:
        return {
          success: false,
          error: '未知的操作类型'
        }
    }
  } catch (error) {
    console.error('业务管理云函数错误:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 创建订单 - 优化版本（支持服务外键）
async function createOrder(wxContext, orderData) {
  const openid = wxContext.OPENID
  const currentTime = new Date()
  
  console.log('📝 开始创建订单')
  console.log('用户openid:', openid)
  console.log('订单数据:', JSON.stringify(orderData, null, 2))
  
  // 数据验证
  if (!orderData.customerName || !orderData.phone) {
    throw new Error('必填字段缺失：客户姓名和电话不能为空')
  }
  
  // 验证服务信息（支持新旧两种方式）
  if (!orderData.serviceId && !orderData.serviceType) {
    throw new Error('必须指定服务信息：serviceId 或 serviceType')
  }
  
  // 获取用户信息
  let userInfo = null
  try {
    const userQuery = await db.collection('users').where({
      openid: openid
    }).get()
    
    if (userQuery.data.length > 0) {
      userInfo = userQuery.data[0]
      console.log('👤 获取到用户信息:', userInfo.nickName || '未知用户')
    } else {
      console.log('⚠️ 未找到用户信息，将创建新用户记录')
    }
  } catch (error) {
    console.warn('获取用户信息失败:', error.message)
  }
  
  // 获取服务信息（如果提供了serviceId）
  let serviceInfo = null
  console.log('🔍 检查serviceId:', orderData.serviceId)
  console.log('🔍 serviceId类型:', typeof orderData.serviceId)
  console.log('🔍 serviceId长度:', orderData.serviceId ? orderData.serviceId.length : 'N/A')

  if (orderData.serviceId) {
    try {
      // 验证serviceId格式
      if (typeof orderData.serviceId === 'string' && orderData.serviceId.length === 24) {
        console.log('✅ serviceId格式验证通过（24位MongoDB ObjectId）')
      } else {
        console.warn('⚠️ serviceId格式异常，但仍尝试查询:', orderData.serviceId)
      }

      console.log('🔗 尝试通过_id字段获取服务信息，serviceId:', orderData.serviceId)
      const serviceResult = await db.collection('services').doc(orderData.serviceId).get()
      if (serviceResult.data) {
        serviceInfo = serviceResult.data
        console.log('✅ 通过_id字段关联服务信息成功:', serviceInfo.title)
        console.log('🔗 确认服务数据库_id:', serviceInfo._id)
        console.log('🔗 serviceId匹配:', orderData.serviceId === serviceInfo._id)
      } else {
        console.log('⚠️ 通过_id字段未找到服务信息，serviceId:', orderData.serviceId)
      }
    } catch (error) {
      console.warn('❌ 通过_id字段获取服务信息失败:', error.message)
      console.warn('serviceId:', orderData.serviceId)
      console.warn('错误详情:', error)
    }
  } else {
    console.log('⚠️ 未提供serviceId，跳过服务关联')
  }
  
  // 生成订单ID
  const timestamp = Date.now()
  const random = Math.random().toString(36).substr(2, 4).toUpperCase()
  const orderId = `ORD${timestamp}${random}`
  
  // 构建订单对象
  const order = {
    id: orderId,
    openid: openid,
    userId: userInfo?.userId || null,
    userDisplayId: userInfo?.displayId || null,
    customerName: orderData.customerName.trim(),
    phone: orderData.phone.trim(),
    company: orderData.company?.trim() || '',
    
    // === 服务关联字段（新） ===
    serviceId: orderData.serviceId || null,
    serviceCategoryCode: serviceInfo?.category || orderData.serviceType || null,
    
    // === 兼容字段（保留） ===
    serviceType: serviceInfo?.category || orderData.serviceType || '',
    serviceTypeLabel: serviceInfo?.title || orderData.serviceTypeLabel || '',
    
    serviceProject: orderData.serviceProject?.trim() || '',
    description: orderData.description?.trim() || '',
    preferredDate: orderData.preferredDate || '',
    preferredTime: orderData.preferredTime || '',
    address: orderData.address?.trim() || '',
    urgency: orderData.urgency || 'normal',
    status: 'pending',
    createTime: currentTime,
    updateTime: currentTime,
    statusHistory: [{
      status: 'pending',
      timestamp: currentTime,
      note: '订单创建'
    }]
  }
  
  console.log('📋 准备插入订单:', orderId)
  
  try {
    // 尝试写入订单数据
    const orderResult = await db.collection('orders').add({
      data: order
    })
    
    console.log('✅ 订单创建成功!')
    console.log('数据库_id:', orderResult._id)
    console.log('🔗 保存的serviceId:', order.serviceId)
    console.log('📋 完整订单数据:', order)
    
    // 创建对应的项目记录
    try {
      const project = await createProjectFromOrder(order)
      console.log('✅ 项目记录创建成功:', project.id)
    } catch (projectError) {
      console.error('❌ 项目记录创建失败:', projectError.message)
      // 项目创建失败不影响订单创建成功
    }
    
    return {
      success: true,
      orderId: orderId,
      data: order,
      message: '订单创建成功'
    }
    
  } catch (error) {
    console.error('❌ 创建订单失败:', error)
    console.error('错误详情:', error.message)
    console.error('完整错误对象:', error)
    
    throw new Error(`创建订单失败: ${error.message}`)
  }
}

// 从订单创建项目
async function createProjectFromOrder(order) {
  const projectId = 'PRJ' + order.id.substring(3)
  
  const project = {
    id: projectId,
    orderId: order.id,
    openid: order.openid,
    userId: order.userId, // 关联用户ID
    userDisplayId: order.userDisplayId, // 关联用户显示ID
    name: `${order.customerName} - ${order.serviceTypeLabel || order.serviceType}`,
    description: order.description,
    clientName: order.customerName,
    clientPhone: order.phone,
    clientCompany: order.company,
    serviceType: order.serviceType,
    status: 'planning', // 规划中
    progress: 5,
    startDate: order.createTime,
    createTime: order.createTime,
    updateTime: order.createTime,
    milestones: [
      { name: '需求确认', status: 'pending', progress: 0 },
      { name: '现场查勘', status: 'pending', progress: 0 },
      { name: '方案设计', status: 'pending', progress: 0 },
      { name: '报价确认', status: 'pending', progress: 0 },
      { name: '项目实施', status: 'pending', progress: 0 },
      { name: '质量验收', status: 'pending', progress: 0 },
      { name: '项目交付', status: 'pending', progress: 0 },
      { name: '售后服务', status: 'pending', progress: 0 }
    ]
  }
  
  await db.collection('projects').add({
    data: project
  })
  
  return project
}

// 获取订单列表
async function getOrders(wxContext, params) {
  const { page = 1, limit = 20, status } = params || {}
  
  let query = db.collection('orders')
  
  if (status) {
    query = query.where({ status })
  }
  
  const result = await query
    .orderBy('createTime', 'desc')
    .skip((page - 1) * limit)
    .limit(limit)
    .get()
  
  return {
    success: true,
    data: result.data,
    total: result.data.length
  }
}

// 获取用户订单
async function getUserOrders(wxContext, params) {
  const { page = 1, limit = 20, status } = params || {}
  const openid = wxContext.OPENID
  
  let whereCondition = { openid }
  if (status) {
    whereCondition.status = status
  }
  
  const result = await db.collection('orders')
    .where(whereCondition)
    .orderBy('createTime', 'desc')
    .skip((page - 1) * limit)
    .limit(limit)
    .get()
  
  return {
    success: true,
    data: result.data,
    total: result.data.length
  }
}

// 更新订单状态
async function updateOrderStatus(wxContext, params) {
  const { orderId, status, note } = params
  const currentTime = new Date()
  
  const result = await db.collection('orders').where({
    id: orderId
  }).update({
    data: {
      status: status,
      updateTime: currentTime,
      statusHistory: _.push([{
        status: status,
        timestamp: currentTime,
        note: note || '',
        operator: wxContext.OPENID
      }])
    }
  })
  
  // 同步更新项目状态
  await updateProjectFromOrder(orderId, status)
  
  return {
    success: true,
    message: '状态更新成功'
  }
}

// 根据订单状态更新项目
async function updateProjectFromOrder(orderId, orderStatus) {
  const projectQuery = await db.collection('projects').where({
    orderId: orderId
  }).get()
  
  if (projectQuery.data.length === 0) {
    return
  }
  
  const project = projectQuery.data[0]
  let projectStatus = project.status
  let progress = project.progress
  let milestones = project.milestones || []
  
  // 根据订单状态更新项目状态和进度
  switch (orderStatus) {
    case 'confirmed':
      projectStatus = 'active'
      progress = 15
      milestones[0] = { ...milestones[0], status: 'completed', progress: 100 }
      break
    case 'surveying':
      projectStatus = 'active'
      progress = 25
      milestones[1] = { ...milestones[1], status: 'in_progress', progress: 50 }
      break
    case 'designing':
      projectStatus = 'active'
      progress = 40
      milestones[1] = { ...milestones[1], status: 'completed', progress: 100 }
      milestones[2] = { ...milestones[2], status: 'in_progress', progress: 50 }
      break
    case 'quoted':
      projectStatus = 'active'
      progress = 55
      milestones[2] = { ...milestones[2], status: 'completed', progress: 100 }
      milestones[3] = { ...milestones[3], status: 'in_progress', progress: 50 }
      break
    case 'in_progress':
      projectStatus = 'active'
      progress = 75
      milestones[3] = { ...milestones[3], status: 'completed', progress: 100 }
      milestones[4] = { ...milestones[4], status: 'in_progress', progress: 50 }
      break
    case 'testing':
      projectStatus = 'testing'
      progress = 90
      milestones[4] = { ...milestones[4], status: 'completed', progress: 100 }
      milestones[5] = { ...milestones[5], status: 'in_progress', progress: 50 }
      break
    case 'completed':
      projectStatus = 'completed'
      progress = 100
      milestones = milestones.map(m => ({ ...m, status: 'completed', progress: 100 }))
      break
  }
  
  await db.collection('projects').doc(project._id).update({
    data: {
      status: projectStatus,
      progress: progress,
      milestones: milestones,
      updateTime: new Date()
    }
  })
}

// 获取订单详情
async function getOrderDetail(wxContext, params) {
  const { orderId } = params
  const openid = wxContext.OPENID
  
  console.log('📋 获取订单详情:', { orderId, openid })
  
  if (!orderId) {
    return {
      success: false,
      error: '订单ID不能为空'
    }
  }
  
  try {
    // 查询订单
    const orderResult = await db.collection('orders').where({
      id: orderId,
      openid: openid
    }).get()
    
    if (orderResult.data.length === 0) {
      return {
        success: false,
        error: '订单不存在或无权限查看'
      }
    }
    
    let order = orderResult.data[0]
    console.log('📦 找到订单:', order.id, '状态:', order.status)
    
    // 如果订单有serviceId，获取完整的服务信息
    if (order.serviceId) {
      try {
        console.log('🔗 获取关联服务信息, serviceId:', order.serviceId)
        const serviceResult = await db.collection('services').doc(order.serviceId).get()
        if (serviceResult.data) {
          order.service = serviceResult.data
          console.log('✅ 关联服务信息获取成功:', order.service.title)
        } else {
          console.log('⚠️ 关联服务信息不存在')
        }
      } catch (error) {
        console.warn('获取关联服务信息失败:', error.message)
      }
    }
    
    // 获取施工队伍信息（如果已分配）
    if (order.teamId) {
      try {
        console.log('👷‍♂️ 获取施工队伍信息, teamId:', order.teamId)
        const teamResult = await db.collection('construction_teams').where({
          teamId: order.teamId
        }).get()
        
        if (teamResult.data.length > 0) {
          const team = teamResult.data[0]
          order.teamName = team.teamName
          order.teamPhone = team.phone
          order.teamAvatar = team.avatar
          order.teamRating = team.rating
          order.teamTypeName = team.typeName
          order.teamCategoryName = team.categoryName
          console.log('✅ 施工队伍信息获取成功:', team.teamName)
        }
      } catch (error) {
        console.warn('获取施工队伍信息失败:', error.message)
      }
    }
    
    return {
      success: true,
      data: order
    }
    
  } catch (error) {
    console.error('获取订单详情失败:', error)
    return {
      success: false,
      error: '获取订单详情失败: ' + error.message
    }
  }
}

// 获取订单操作历史
async function getOrderHistory(wxContext, params) {
  const { orderId } = params
  
  try {
    const result = await db.collection('order_actions')
      .where({ orderId })
      .orderBy('createTime', 'desc')
      .get()
    
    return {
      success: true,
      data: result.data
    }
  } catch (error) {
    console.error('获取订单历史失败:', error)
    return {
      success: false,
      error: '获取订单历史失败'
    }
  }
}

// 创建项目
async function createProject(wxContext, projectData) {
  const openid = wxContext.OPENID
  const currentTime = new Date()
  
  const project = {
    id: `PRJ${Date.now()}${Math.random().toString(36).substr(2, 4).toUpperCase()}`,
    name: projectData.name,
    description: projectData.description || '',
    status: 'planning',
    createTime: currentTime,
    updateTime: currentTime,
    openid: openid
  }
  
  const result = await db.collection('projects').add({
    data: project
  })
  
  return {
    success: true,
    projectId: project.id,
    message: '项目创建成功'
  }
}

// 获取项目列表
async function getProjects(wxContext, params) {
  const { page = 1, limit = 20 } = params || {}
  const openid = wxContext.OPENID
  
  const result = await db.collection('projects')
    .where({ openid })
    .orderBy('createTime', 'desc')
    .skip((page - 1) * limit)
    .limit(limit)
    .get()
  
  return {
    success: true,
    data: result.data
  }
}

// 更新项目
async function updateProject(wxContext, params) {
  const { projectId, projectData } = params
  const openid = wxContext.OPENID
  const currentTime = new Date()
  
  if (!projectId) {
    return {
      success: false,
      error: '项目ID不能为空'
    }
  }
  
  try {
    // 检查项目是否存在且属于当前用户
    const projectQuery = await db.collection('projects').where({
      id: projectId,
      openid: openid
    }).get()
    
    if (projectQuery.data.length === 0) {
      return {
        success: false,
        error: '项目不存在或无权限修改'
      }
    }
    
    // 构建更新数据
    const updateData = {
      updateTime: currentTime
    }
    
    // 只更新提供的字段
    if (projectData.name !== undefined) {
      updateData.name = projectData.name.trim()
    }
    if (projectData.description !== undefined) {
      updateData.description = projectData.description.trim()
    }
    if (projectData.status !== undefined) {
      updateData.status = projectData.status
    }
    if (projectData.progress !== undefined) {
      updateData.progress = Math.min(100, Math.max(0, projectData.progress))
    }
    if (projectData.startDate !== undefined) {
      updateData.startDate = projectData.startDate
    }
    if (projectData.endDate !== undefined) {
      updateData.endDate = projectData.endDate
    }
    if (projectData.milestones !== undefined) {
      updateData.milestones = projectData.milestones
    }
    
    // 更新项目
    await db.collection('projects').where({
      id: projectId,
      openid: openid
    }).update({
      data: updateData
    })
    
    return {
      success: true,
      message: '项目更新成功'
    }
    
  } catch (error) {
    console.error('更新项目失败:', error)
    return {
      success: false,
      error: '更新项目失败: ' + error.message
    }
  }
}

// 获取项目详情
async function getProjectDetail(wxContext, params) {
  const { projectId } = params
  const openid = wxContext.OPENID
  
  const result = await db.collection('projects')
    .where({ id: projectId, openid })
    .get()
  
  if (result.data.length === 0) {
    return {
      success: false,
      error: '项目不存在'
    }
  }
  
  return {
    success: true,
    data: result.data[0]
  }
}

// 获取统计数据
async function getStats(wxContext) {
  const openid = wxContext.OPENID
  
  try {
    // 获取订单统计
    const orderStats = await db.collection('orders')
      .where({ openid })
      .get()
    
    const orders = orderStats.data
    const totalOrders = orders.length
    const pendingOrders = orders.filter(o => o.status === 'pending').length
    const completedOrders = orders.filter(o => o.status === 'completed').length
    const cancelledOrders = orders.filter(o => o.status === 'cancelled').length
    
    // 获取项目统计
    const projectStats = await db.collection('projects')
      .where({ openid })
      .get()
    
    const projects = projectStats.data
    const totalProjects = projects.length
    const activeProjects = projects.filter(p => ['planning', 'in_progress'].includes(p.status)).length
    
    return {
      success: true,
      data: {
        orders: {
          total: totalOrders,
          pending: pendingOrders,
          completed: completedOrders,
          cancelled: cancelledOrders
        },
        projects: {
          total: totalProjects,
          active: activeProjects
        }
      }
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    return {
      success: false,
      error: '获取统计数据失败'
    }
  }
}

// 批量创建服务项目
async function batchCreateServices(wxContext, params) {
  const { services } = params
  
  if (!services || !Array.isArray(services)) {
    return {
      success: false,
      error: '服务数据格式错误'
    }
  }
  
  try {
    const results = []
    for (const service of services) {
      const serviceData = {
        ...service,
        createTime: new Date(),
        updateTime: new Date()
      }
      
      const result = await db.collection('services').add({
        data: serviceData
      })
      
      results.push(result._id)
    }
    
    return {
      success: true,
      data: results,
      message: `成功创建 ${results.length} 个服务项目`
    }
  } catch (error) {
    console.error('批量创建服务失败:', error)
    return {
      success: false,
      error: '批量创建服务失败'
    }
  }
}

// 修复订单serviceId关联
async function fixOrderServiceId(wxContext, params) {
  try {
    const orders = await db.collection('orders').get()
    const services = await db.collection('services').get()
    
    let fixedCount = 0
    
    for (const order of orders.data) {
      if (!order.serviceId && order.serviceType) {
        // 根据serviceType查找对应的服务
        const matchedService = services.data.find(s => 
          s.category === order.serviceType || s.title === order.serviceTypeLabel
        )
        
        if (matchedService) {
          await db.collection('orders').doc(order._id).update({
            data: {
              serviceId: matchedService._id,
              serviceCategoryCode: matchedService.category
            }
          })
          fixedCount++
        }
      }
    }
    
    return {
      success: true,
      message: `修复了 ${fixedCount} 个订单的服务关联`
    }
  } catch (error) {
    console.error('修复订单服务关联失败:', error)
    return {
      success: false,
      error: '修复失败'
    }
  }
}

// 提交客服留言
async function submitMessage(wxContext, params) {
  const { message, contact, category } = params
  const openid = wxContext.OPENID
  
  if (!message || !contact) {
    return {
      success: false,
      error: '留言内容和联系方式不能为空'
    }
  }
  
  try {
    const messageData = {
      openid: openid,
      message: message.trim(),
      contact: contact.trim(),
      category: category || 'general',
      status: 'pending',
      createTime: new Date(),
      updateTime: new Date()
    }
    
    const result = await db.collection('customer_messages').add({
      data: messageData
    })
    
    return {
      success: true,
      messageId: result._id,
      message: '留言提交成功，我们会尽快回复您'
    }
  } catch (error) {
    console.error('提交留言失败:', error)
    return {
      success: false,
      error: '提交失败，请稍后重试'
    }
  }
}

// 记录客服咨询
async function logCustomerService(wxContext, params) {
  const { type, content } = params
  const openid = wxContext.OPENID
  
  try {
    const logData = {
      openid: openid,
      type: type || 'contact',
      content: content || '',
      createTime: new Date()
    }
    
    await db.collection('customer_service_logs').add({
      data: logData
    })
    
    return {
      success: true,
      message: '客服咨询记录成功'
    }
  } catch (error) {
    console.error('记录客服咨询失败:', error)
    return {
      success: false,
      error: '记录失败'
    }
  }
}

// 获取服务列表
async function getServices() {
  try {
    const result = await db.collection('services')
      .orderBy('createTime', 'desc')
      .get()
    
    return {
      success: true,
      data: result.data
    }
  } catch (error) {
    console.error('获取服务列表失败:', error)
    return {
      success: false,
      error: '获取服务列表失败'
    }
  }
}

// 预订服务
async function bookService(wxContext, serviceData) {
  // 直接调用创建订单功能
  return await createOrder(wxContext, serviceData)
}

// 取消订单
async function cancelOrder(wxContext, params) {
  const { orderId, reason, needTeamApproval } = params
  const currentTime = new Date()
  
  console.log('📋 开始取消订单:', { orderId, reason, needTeamApproval })
  
  // 获取当前订单
  const orderQuery = await db.collection('orders').where({
    id: orderId,
    openid: wxContext.OPENID
  }).get()
  
  if (orderQuery.data.length === 0) {
    return {
      success: false,
      error: '订单不存在或无权限操作'
    }
  }
  
  const order = orderQuery.data[0]
  
  // 检查订单状态是否可以取消
  const cancelableStatuses = ['pending', 'confirmed', 'waiting_team', 'surveying', 'designing', 'quoted']
  if (!cancelableStatuses.includes(order.status)) {
    return {
      success: false,
      error: '当前订单状态不允许取消'
    }
  }
  
  // 更新订单状态和取消信息
  const updateData = {
    status: 'cancelled',
    updateTime: currentTime,
    cancelTime: currentTime,
    cancelReason: reason || '用户主动取消',
    cancelBy: wxContext.OPENID
  }
  
  // 添加状态历史记录
  if (order.statusHistory) {
    updateData.statusHistory = _.push([{
      status: 'cancelled',
      timestamp: currentTime,
      note: `订单已取消，原因：${reason || '用户主动取消'}`,
      operator: wxContext.OPENID
    }])
  }
  
  await db.collection('orders').doc(order._id).update({
    data: updateData
  })
  
  // 记录操作历史
  try {
    await db.collection('order_actions').add({
      data: {
        orderId: orderId,
        action: '取消订单',
        note: `取消原因：${reason || '用户主动取消'}`,
        operator: wxContext.OPENID,
        createTime: currentTime
      }
    })
  } catch (error) {
    console.warn('记录操作历史失败:', error.message)
  }
  
  // 同步更新项目状态
  await updateProjectFromOrder(orderId, 'cancelled')
  
  console.log('✅ 订单取消成功:', orderId)
  
  return {
    success: true,
    message: '订单取消成功'
  }
}

// 申请取消订单
async function requestCancelOrder(wxContext, params) {
  const { orderId, reason } = params
  const currentTime = new Date()
  
  console.log('📋 开始申请取消订单:', { orderId, reason })
  
  // 获取当前订单
  const orderQuery = await db.collection('orders').where({
    id: orderId,
    openid: wxContext.OPENID
  }).get()
  
  if (orderQuery.data.length === 0) {
    return {
      success: false,
      error: '订单不存在或无权限操作'
    }
  }
  
  const order = orderQuery.data[0]
  
  // 检查订单是否已被施工队伍接单
  const teamAcceptedStatuses = ['team_accepted', 'team_preparing', 'team_on_site', 'in_progress', 'paused', 'testing']
  if (!teamAcceptedStatuses.includes(order.status)) {
    // 如果还没有被施工队伍接单，直接取消
    return await cancelOrder(wxContext, { orderId, reason, needTeamApproval: false })
  }
  
  // 更新订单状态为申请取消
  const updateData = {
    status: 'cancel_pending',
    updateTime: currentTime,
    cancelRequestTime: currentTime,
    cancelRequestReason: reason || '用户申请取消',
    cancelRequestBy: wxContext.OPENID
  }
  
  // 添加状态历史记录
  if (order.statusHistory) {
    updateData.statusHistory = _.push([{
      status: 'cancel_pending',
      timestamp: currentTime,
      note: `客户申请取消订单，原因：${reason || '用户申请取消'}，等待施工队伍确认`,
      operator: wxContext.OPENID
    }])
  }
  
  await db.collection('orders').doc(order._id).update({
    data: updateData
  })
  
  // 记录操作历史
  try {
    await db.collection('order_actions').add({
      data: {
        orderId: orderId,
        action: '申请取消订单',
        note: `申请原因：${reason || '用户申请取消'}，等待施工队伍确认`,
        operator: wxContext.OPENID,
        createTime: currentTime
      }
    })
  } catch (error) {
    console.warn('记录操作历史失败:', error.message)
  }
  
  // 同步更新项目状态
  await updateProjectFromOrder(orderId, 'cancel_pending')
  
  // TODO: 发送通知给施工队伍
  // 这里可以调用消息推送功能通知施工队伍有取消申请
  
  console.log('✅ 订单取消申请提交成功:', orderId)
  
  return {
    success: true,
    message: '取消申请已提交，等待施工队伍确认'
  }
}

// 处理取消申请
async function processCancelRequest(wxContext, params) {
  const { orderId } = params
  const currentTime = new Date()
  
  // 获取当前订单
  const orderQuery = await db.collection('orders').where({
    id: orderId,
    openid: wxContext.OPENID
  }).get()
  
  if (orderQuery.data.length === 0) {
    return {
      success: false,
      error: '订单不存在'
    }
  }
  
  const order = orderQuery.data[0]
  
  // 更新订单状态为已取消
  await db.collection('orders').doc(order._id).update({
    data: {
      status: 'cancelled',
      updateTime: currentTime
    }
  })
  
  // 同步更新项目状态
  await updateProjectFromOrder(orderId, 'cancelled')
  
  return {
    success: true,
    message: '取消申请处理成功'
  }
}

// ========== 管理员功能 ==========

// 获取管理员订单列表
async function getAdminOrders(wxContext, params) {
  const { page = 1, limit = 20, status, teamId, dateRange } = params || {}
  
  try {
    let whereCondition = {}
    
    if (status && status !== 'all') {
      whereCondition.status = status
    }
    
    if (teamId) {
      whereCondition.teamId = teamId
    }
    
    if (dateRange && dateRange.start && dateRange.end) {
      whereCondition.createTime = _.gte(new Date(dateRange.start)).and(_.lte(new Date(dateRange.end)))
    }
    
    const result = await db.collection('orders')
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((page - 1) * limit)
      .limit(limit)
      .get()
    
    // 获取每个订单的详细信息（包括用户信息、团队信息等）
    const enhancedOrders = await Promise.all(result.data.map(async (order) => {
      // 获取用户信息
      if (order.openid) {
        try {
          const userResult = await db.collection('users').where({ openid: order.openid }).get()
          if (userResult.data.length > 0) {
            order.userInfo = userResult.data[0]
          }
        } catch (error) {
          console.warn('获取用户信息失败:', error.message)
        }
      }
      
      // 获取团队信息
      if (order.teamId) {
        try {
          const teamResult = await db.collection('construction_teams').where({ teamId: order.teamId }).get()
          if (teamResult.data.length > 0) {
            order.teamInfo = teamResult.data[0]
          }
        } catch (error) {
          console.warn('获取团队信息失败:', error.message)
        }
      }
      
      return order
    }))
    
    return {
      success: true,
      data: enhancedOrders,
      total: result.data.length
    }
  } catch (error) {
    console.error('获取管理员订单列表失败:', error)
    return {
      success: false,
      error: '获取订单列表失败'
    }
  }
}

// 获取管理员统计数据
async function getAdminStats(wxContext, params) {
  try {
    // 获取订单统计
    const allOrders = await db.collection('orders').get()
    const orders = allOrders.data
    
    // 获取用户统计
    const allUsers = await db.collection('users').get()
    const users = allUsers.data
    
    // 获取团队统计
    const allTeams = await db.collection('construction_teams').get()
    const teams = allTeams.data
    
    // 获取项目统计
    const allProjects = await db.collection('projects').get()
    const projects = allProjects.data
    
    // 计算各种统计数据
    const stats = {
      orders: {
        total: orders.length,
        pending: orders.filter(o => o.status === 'pending').length,
        confirmed: orders.filter(o => o.status === 'confirmed').length,
        inProgress: orders.filter(o => ['team_accepted', 'surveying', 'designing', 'quoted', 'in_progress'].includes(o.status)).length,
        completed: orders.filter(o => o.status === 'completed').length,
        cancelled: orders.filter(o => o.status === 'cancelled').length,
        cancelPending: orders.filter(o => o.status === 'cancel_pending').length
      },
      users: {
        total: users.length,
        active: users.filter(u => u.lastLoginTime && new Date() - new Date(u.lastLoginTime) < 30 * 24 * 60 * 60 * 1000).length,
        newThisMonth: users.filter(u => u.createTime && new Date() - new Date(u.createTime) < 30 * 24 * 60 * 60 * 1000).length
      },
      teams: {
        total: teams.length,
        active: teams.filter(t => t.status === 'active').length,
        busy: teams.filter(t => t.status === 'busy').length,
        pending: teams.filter(t => t.auditStatus === 'pending').length
      },
      projects: {
        total: projects.length,
        planning: projects.filter(p => p.status === 'planning').length,
        inProgress: projects.filter(p => p.status === 'in_progress').length,
        testing: projects.filter(p => p.status === 'testing').length,
        completed: projects.filter(p => p.status === 'completed').length
      },
      revenue: {
        thisMonth: calculateMonthlyRevenue(orders),
        lastMonth: calculateLastMonthRevenue(orders),
        total: calculateTotalRevenue(orders)
      }
    }
    
    return {
      success: true,
      data: stats
    }
  } catch (error) {
    console.error('获取管理员统计数据失败:', error)
    return {
      success: false,
      error: '获取统计数据失败'
    }
  }
}

// 分配团队
async function assignTeam(wxContext, params) {
  const { orderId, teamId, note } = params
  const currentTime = new Date()
  
  try {
    // 检查订单是否存在
    const orderResult = await db.collection('orders').where({ id: orderId }).get()
    if (orderResult.data.length === 0) {
      return {
        success: false,
        error: '订单不存在'
      }
    }
    
    const order = orderResult.data[0]
    
    // 检查团队是否存在
    const teamResult = await db.collection('construction_teams').where({ teamId: teamId }).get()
    if (teamResult.data.length === 0) {
      return {
        success: false,
        error: '施工团队不存在'
      }
    }
    
    const team = teamResult.data[0]
    
    // 更新订单信息
    await db.collection('orders').doc(order._id).update({
      data: {
        teamId: teamId,
        teamName: team.teamName,
        status: 'team_assigned',
        updateTime: currentTime,
        statusHistory: _.push([{
          status: 'team_assigned',
          timestamp: currentTime,
          note: `分配给团队：${team.teamName}${note ? '，备注：' + note : ''}`,
          operator: wxContext.OPENID
        }])
      }
    })
    
    // 记录操作历史
    await db.collection('order_actions').add({
      data: {
        orderId: orderId,
        action: '分配团队',
        note: `分配给团队：${team.teamName}${note ? '，备注：' + note : ''}`,
        operator: wxContext.OPENID,
        createTime: currentTime
      }
    })
    
    // 发送通知给团队
    await db.collection('notifications').add({
      data: {
        openid: team.openid || team.managerOpenid,
        type: 'team_assignment',
        title: '新订单分配',
        content: `您的团队收到新订单：${order.serviceTypeLabel || order.serviceType}`,
        orderId: orderId,
        isRead: false,
        createTime: currentTime
      }
    })
    
    return {
      success: true,
      message: '团队分配成功'
    }
  } catch (error) {
    console.error('分配团队失败:', error)
    return {
      success: false,
      error: '分配团队失败'
    }
  }
}

// ========== 团队订单管理 ==========

// 获取团队订单
async function getTeamOrders(wxContext, params) {
  const { teamId, status, page = 1, limit = 20 } = params || {}
  const openid = wxContext.OPENID
  
  try {
    // 获取团队信息
    const teamResult = await db.collection('construction_teams').where({
      $or: [
        { openid: openid },
        { managerOpenid: openid },
        { memberOpenids: openid }
      ]
    }).get()
    
    if (teamResult.data.length === 0) {
      return {
        success: false,
        error: '您不属于任何施工团队'
      }
    }
    
    const team = teamResult.data[0]
    const actualTeamId = teamId || team.teamId
    
    // 构建查询条件
    let whereCondition = { teamId: actualTeamId }
    if (status && status !== 'all') {
      whereCondition.status = status
    }
    
    const result = await db.collection('orders')
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((page - 1) * limit)
      .limit(limit)
      .get()
    
    return {
      success: true,
      data: result.data,
      teamInfo: team
    }
  } catch (error) {
    console.error('获取团队订单失败:', error)
    return {
      success: false,
      error: '获取团队订单失败'
    }
  }
}

// 接受团队订单
async function acceptTeamOrder(wxContext, params) {
  const { orderId, estimatedDuration, note } = params
  const currentTime = new Date()
  
  try {
    // 检查订单
    const orderResult = await db.collection('orders').where({ id: orderId }).get()
    if (orderResult.data.length === 0) {
      return {
        success: false,
        error: '订单不存在'
      }
    }
    
    const order = orderResult.data[0]
    
    // 检查是否有权限操作此订单
    const teamResult = await db.collection('construction_teams').where({
      teamId: order.teamId,
      $or: [
        { openid: wxContext.OPENID },
        { managerOpenid: wxContext.OPENID }
      ]
    }).get()
    
    if (teamResult.data.length === 0) {
      return {
        success: false,
        error: '无权限操作此订单'
      }
    }
    
    // 更新订单状态
    await db.collection('orders').doc(order._id).update({
      data: {
        status: 'team_accepted',
        acceptTime: currentTime,
        estimatedDuration: estimatedDuration,
        updateTime: currentTime,
        statusHistory: _.push([{
          status: 'team_accepted',
          timestamp: currentTime,
          note: `团队已接单${estimatedDuration ? '，预计工期：' + estimatedDuration : ''}${note ? '，备注：' + note : ''}`,
          operator: wxContext.OPENID
        }])
      }
    })
    
    // 记录操作历史
    await db.collection('order_actions').add({
      data: {
        orderId: orderId,
        action: '团队接单',
        note: `团队已接单${estimatedDuration ? '，预计工期：' + estimatedDuration : ''}${note ? '，备注：' + note : ''}`,
        operator: wxContext.OPENID,
        createTime: currentTime
      }
    })
    
    // 发送通知给客户
    await db.collection('notifications').add({
      data: {
        openid: order.openid,
        type: 'order_accepted',
        title: '订单已被接受',
        content: `您的订单已被施工团队接受，预计工期：${estimatedDuration || '待确定'}`,
        orderId: orderId,
        isRead: false,
        createTime: currentTime
      }
    })
    
    return {
      success: true,
      message: '订单接受成功'
    }
  } catch (error) {
    console.error('接受团队订单失败:', error)
    return {
      success: false,
      error: '接受订单失败'
    }
  }
}

// 更新订单进度
async function updateOrderProgress(wxContext, params) {
  const { orderId, progress, milestone, note, images } = params
  const currentTime = new Date()
  
  try {
    // 检查订单
    const orderResult = await db.collection('orders').where({ id: orderId }).get()
    if (orderResult.data.length === 0) {
      return {
        success: false,
        error: '订单不存在'
      }
    }
    
    const order = orderResult.data[0]
    
    // 更新数据
    const updateData = {
      updateTime: currentTime
    }
    
    if (progress !== undefined) {
      updateData.progress = Math.min(100, Math.max(0, progress))
    }
    
    if (milestone) {
      updateData.currentMilestone = milestone
    }
    
    if (images && images.length > 0) {
      updateData.progressImages = _.push(images.map(img => ({
        url: img,
        uploadTime: currentTime,
        description: note || ''
      })))
    }
    
    // 添加进度历史
    updateData.statusHistory = _.push([{
      status: order.status,
      timestamp: currentTime,
      note: `进度更新：${progress}%${milestone ? '，里程碑：' + milestone : ''}${note ? '，' + note : ''}`,
      operator: wxContext.OPENID,
      progress: progress,
      milestone: milestone
    }])
    
    await db.collection('orders').doc(order._id).update({
      data: updateData
    })
    
    // 记录操作历史
    await db.collection('order_actions').add({
      data: {
        orderId: orderId,
        action: '更新进度',
        note: `进度：${progress}%${milestone ? '，里程碑：' + milestone : ''}${note ? '，' + note : ''}`,
        operator: wxContext.OPENID,
        createTime: currentTime,
        progress: progress,
        milestone: milestone,
        images: images
      }
    })
    
    // 发送进度通知给客户
    await db.collection('notifications').add({
      data: {
        openid: order.openid,
        type: 'progress_update',
        title: '项目进度更新',
        content: `您的订单进度已更新至${progress}%${milestone ? '，当前阶段：' + milestone : ''}`,
        orderId: orderId,
        isRead: false,
        createTime: currentTime
      }
    })
    
    return {
      success: true,
      message: '进度更新成功'
    }
  } catch (error) {
    console.error('更新订单进度失败:', error)
    return {
      success: false,
      error: '更新进度失败'
    }
  }
}

// ========== 通知管理 ==========

// 发送通知
async function sendNotification(wxContext, params) {
  const { targetOpenid, type, title, content, orderId, projectId } = params
  const currentTime = new Date()
  
  try {
    const notification = {
      openid: targetOpenid,
      type: type || 'general',
      title: title,
      content: content,
      isRead: false,
      createTime: currentTime,
      senderOpenid: wxContext.OPENID
    }
    
    if (orderId) {
      notification.orderId = orderId
    }
    
    if (projectId) {
      notification.projectId = projectId
    }
    
    await db.collection('notifications').add({
      data: notification
    })
    
    return {
      success: true,
      message: '通知发送成功'
    }
  } catch (error) {
    console.error('发送通知失败:', error)
    return {
      success: false,
      error: '发送通知失败'
    }
  }
}

// ========== 数据导出 ==========

// 导出订单数据
async function exportOrderData(wxContext, params) {
  const { dateRange, status, format = 'json' } = params || {}
  
  try {
    let whereCondition = {}
    
    if (status && status !== 'all') {
      whereCondition.status = status
    }
    
    if (dateRange && dateRange.start && dateRange.end) {
      whereCondition.createTime = _.gte(new Date(dateRange.start)).and(_.lte(new Date(dateRange.end)))
    }
    
    const result = await db.collection('orders')
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .get()
    
    // 简化数据结构，只包含需要导出的字段
    const exportData = result.data.map(order => ({
      订单编号: order.id,
      客户姓名: order.customerName,
      联系电话: order.phone,
      服务类型: order.serviceTypeLabel || order.serviceType,
      订单状态: getStatusText(order.status),
      创建时间: formatDate(order.createTime),
      更新时间: formatDate(order.updateTime),
      描述: order.description || '',
      地址: order.address || '',
      团队名称: order.teamName || ''
    }))
    
    return {
      success: true,
      data: exportData,
      total: exportData.length,
      format: format
    }
  } catch (error) {
    console.error('导出订单数据失败:', error)
    return {
      success: false,
      error: '导出数据失败'
    }
  }
}

// ========== 辅助函数 ==========

// 计算月度营收
function calculateMonthlyRevenue(orders) {
  const thisMonth = new Date()
  thisMonth.setDate(1)
  thisMonth.setHours(0, 0, 0, 0)
  
  return orders
    .filter(order => 
      order.status === 'completed' && 
      new Date(order.createTime) >= thisMonth
    )
    .reduce((total, order) => total + (order.amount || 0), 0)
}

// 计算上月营收
function calculateLastMonthRevenue(orders) {
  const lastMonth = new Date()
  lastMonth.setMonth(lastMonth.getMonth() - 1)
  lastMonth.setDate(1)
  lastMonth.setHours(0, 0, 0, 0)
  
  const thisMonth = new Date()
  thisMonth.setDate(1)
  thisMonth.setHours(0, 0, 0, 0)
  
  return orders
    .filter(order => 
      order.status === 'completed' && 
      new Date(order.createTime) >= lastMonth &&
      new Date(order.createTime) < thisMonth
    )
    .reduce((total, order) => total + (order.amount || 0), 0)
}

// 计算总营收
function calculateTotalRevenue(orders) {
  return orders
    .filter(order => order.status === 'completed')
    .reduce((total, order) => total + (order.amount || 0), 0)
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    'pending': '待处理',
    'confirmed': '已确认',
    'team_assigned': '已分配团队',
    'team_accepted': '团队已接单',
    'surveying': '现场查勘',
    'designing': '方案设计',
    'quoted': '已报价',
    'in_progress': '施工中',
    'testing': '验收测试',
    'completed': '已完成',
    'cancelled': '已取消',
    'cancel_pending': '取消申请中'
  }
  return statusMap[status] || status
}

// 格式化日期
function formatDate(date) {
  if (!date) return ''
  const d = new Date(date)
  return d.getFullYear() + '-' + 
         String(d.getMonth() + 1).padStart(2, '0') + '-' + 
         String(d.getDate()).padStart(2, '0') + ' ' +
         String(d.getHours()).padStart(2, '0') + ':' + 
         String(d.getMinutes()).padStart(2, '0')
} 